package com.ruoyi.file.annotation;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;


@Aspect
@Component
@Slf4j
public class FTPClientAspect {

    @Value("${ftp.host}")
    public String host;
    @Value("${ftp.port}")
    public Integer port;
    @Value("${ftp.username}")
    public String username;
    @Value("${ftp.password}")
    public String password;

    @Pointcut("@annotation(FTPClientAnnotation)")
    public void annotationPointcut() {

    }

    @Before("annotationPointcut()")
    public void beforePointcut(JoinPoint joinPoint) throws IOException {
        //获取传入目标方法的参数
        Object[] args = joinPoint.getArgs();
        FTPClient ftpClient = (FTPClient) args[0];
        getFTPClient(ftpClient);
    }

    @After("annotationPointcut()")
    public void afterPointcut(JoinPoint joinPoint) throws IOException {
        Object[] args = joinPoint.getArgs();
        FTPClient ftpClient = (FTPClient) args[0];
        ftpClient.logout();
    }


    //连接获取ftpClient
    public FTPClient getFTPClient(FTPClient ftpClient) throws IOException {

        ftpClient.connect(host, port);
        ftpClient.login(username, password);
        boolean login = ftpClient.login(username, password);
        if (!login) {
            log.info("connected fail...");
            return null;
        }
        if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();
            log.info("FTP server refused connection...");
            return null;
        }
        return ftpClient;
    }



}
